import { listStore } from '@/stores'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import sOrderConfig from '@/pages/order/short-order/components/order-item/orderTabsConfig.js'
import lOrderConfig from '@/pages/order/long-order/components/order-item/orderTabsConfig.js'
/**
 * 页面跳转
 * updateQueryParam 要更新的queryParam
 * orderType 订单类型{长租|短租}
 * targetUrl 跳转的页面
 */
export function useOrderNavigateTo(updateQueryParam = {}, orderType = 'short-order') {
  const listQueryStore = listStore()
  // 更新queryParam
  const { keywords, orderStatus, orderLabels, siteId, siteName } = updateQueryParam
  // 更新 vuex
  if (orderType == 'short-order') {
    const activedSort = sOrderConfig.tabsConfigList.find((item) => item.value == orderStatus).defaultSort
    let newParam = {
      keywords,
      orderStatus,
      orderLabels,
      siteId,
      siteName,
      sortField: activedSort.value,
      sortType: activedSort.sort,
    }
    listQueryStore.updateSOrderQueryParam(newParam)
    listQueryStore.updateOrderActiveTab('short-order')
  } else {
    const activedSort = lOrderConfig.tabsConfigList.find((item) => item.value == orderStatus).defaultSort
    let newParam = {
      keywords,
      status: orderStatus,
      orderLableList: orderLabels,
      siteId,
      siteName,
      sortField: activedSort.value,
      sortType: activedSort.sort,
    }
    listQueryStore.updateLOrderQueryParam(newParam)
    listQueryStore.updateOrderActiveTab('long-order')
  }
  uni.$emit('order_loadData')
  uni.switchTab({ url: '/pages/order/order' })
}
/**
 * 页面跳转
 */
export function useOrderRedirectTo(orderType = 'short-order') {
  useOrderNavigateTo(
    {
      orderStatus: undefined,
      orderLabels: [],
    },
    orderType,
  )
}
/**
 * 返回列表并派发刷新页面 & 热更新逻辑
 */
export function useLoadDataAndHotUpdateNavigateBack() {
  // 刷新页面
  uni.$emit('loadData')
  // 订单热更新
  uni.$emit('order_hotUpdate')
  // 返回上一级页面
  uni.navigateBack()
}
/**
 * 事件绑定 hook
 * @param {*} refreshFn
 * @param {*} orderHotUpdateFn
 */
export function useBindEventOn({ orderLoadData, orderHotUpdate }) {
  onLoad(() => {
    uni.$on('order_loadData', orderLoadData)
    uni.$on('order_hotUpdate', orderHotUpdate)
  })
  onUnload(() => {
    uni.$on('order_loadData', orderLoadData)
    uni.$on('order_hotUpdate', orderHotUpdate)
  })
}
